#include "Timer.h"
#include "driver_timer.h"
#include "string.h"

static TimerCallback_t sTimerCb;           //回调函数 


void Timer_Init(void)
{
    timer_init();

	memset(&sTimerCb.arrayCallback, 0x00, sizeof(sTimerCb.arrayCallback));
	sTimerCb.nTimers = 0;
}

bool Create_Timer(TimerCallback cb, uint16_t nMilliSeconds)
{
	bool bSuccess = false;
	
	if (sTimerCb.nTimers < MAX_TIMERS_SIZE)
	{
		sTimerCb.arrayCallback[sTimerCb.nTimers] = cb;
		sTimerCb.nTimerCount[sTimerCb.nTimers] = nMilliSeconds / 10;
		sTimerCb.nTimerCountBak[sTimerCb.nTimers] = nMilliSeconds / 10;
		sTimerCb.nTimers++;
		bSuccess = true;
	}
	else
	{
		bSuccess = false;
	}
	
	return bSuccess;
}

void OnTick()
{
	for(int i = 0; i < sTimerCb.nTimers; i++)
	{
		sTimerCb.nTimerCount[i]--;
		if (0 == sTimerCb.nTimerCount[i])
		{
			sTimerCb.arrayCallback[i]();
			sTimerCb.nTimerCount[i] = sTimerCb.nTimerCountBak[i];
		}
	}
}


#ifdef __cplusplus
extern "C" {
#endif

	
//在C++中定义中断响应函数必须要extern c
void TIM2_IRQHandler(void)
{
	OnTick();
	TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
#ifdef __cplusplus
}
#endif
